package org.dromara.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.dromara.business.domain.UserInfoWeb;
import org.dromara.business.mapper.UserInfoMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.UserFollowBo;
import org.dromara.business.domain.vo.UserFollowVo;
import org.dromara.business.domain.UserFollow;
import org.dromara.business.mapper.UserFollowMapper;
import org.dromara.business.service.IUserFollowService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户关注Service业务层处理
 *
 * @author Hao Tong Xue
 * @date 2025-04-03
 */
@RequiredArgsConstructor
@Service
public class UserFollowServiceImpl implements IUserFollowService {

    private final UserFollowMapper baseMapper;
    private final UserInfoMapper userInfoMapper;

    /**
     * 查询用户关注
     *
     * @param id 主键
     * @return 用户关注
     */
    @Override
    public UserFollowVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户关注列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户关注分页列表
     */
    @Override
    public TableDataInfo<UserFollowVo> queryPageList(UserFollowBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserFollow> lqw = buildQueryWrapper(bo);
        Page<UserFollowVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户关注列表
     *
     * @param bo 查询条件
     * @return 用户关注列表
     */
    @Override
    public List<UserFollowVo> queryList(UserFollowBo bo) {
        LambdaQueryWrapper<UserFollow> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserFollow> buildQueryWrapper(UserFollowBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserFollow> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(UserFollow::getId);
        lqw.eq(bo.getFollowerId() != null, UserFollow::getFollowerId, bo.getFollowerId());
        lqw.eq(bo.getFollowingId() != null, UserFollow::getFollowingId, bo.getFollowingId());
        return lqw;
    }

    /**
     * 新增用户关注
     *
     * @param bo 用户关注
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserFollowBo bo) {

        LambdaQueryWrapper<UserFollow> queryWrapper = Wrappers.<UserFollow>lambdaQuery().eq(UserFollow::getFollowerId, LoginHelper.getUserId()).eq(UserFollow::getFollowingId, bo.getFollowingId());

        List<UserFollow> userFollows = baseMapper.selectList(queryWrapper);
        if(bo.getOperateType() == 1 && CollUtil.isNotEmpty(userFollows)){
            return true;
        }

        UserInfoWeb userInfoWeb = userInfoMapper.selectById(LoginHelper.getUserId());
        userInfoWeb.setFollowNum(bo.getOperateType() == 1 ? userInfoWeb.getFollowNum() + 1 : userInfoWeb.getFollowNum() - 1);
        userInfoMapper.updateById(userInfoWeb);

        userInfoWeb = userInfoMapper.selectById(bo.getFollowingId());
        userInfoWeb.setId(bo.getFollowingId());
        userInfoWeb.setFansNum(bo.getOperateType() == 1 ? userInfoWeb.getFansNum() + 1 : userInfoWeb.getFansNum() - 1);
        userInfoMapper.updateById(userInfoWeb);

        if (bo.getOperateType() == 1) { // 关注
            UserFollow add = MapstructUtils.convert(bo, UserFollow.class);
            validEntityBeforeSave(add);
            add.setFollowerId(LoginHelper.getUserId());
            return baseMapper.insert(add) > 0;
        }else {
            return baseMapper.delete(queryWrapper) > 0;
        }

    }

    /**
     * 修改用户关注
     *
     * @param bo 用户关注
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserFollowBo bo) {
        UserFollow update = MapstructUtils.convert(bo, UserFollow.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserFollow entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户关注信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     *  查询登录用户是否关注当前用户
     * @param followingId 被关注者的用户 ID
     * @return true | false
     */
    @Override
    public Boolean statusFollow(Long followingId) {
        UserFollow userFollow = baseMapper.selectOne(Wrappers.<UserFollow>lambdaQuery().eq(UserFollow::getFollowingId, followingId).eq(UserFollow::getFollowerId, LoginHelper.getUserId()));
        return userFollow != null;
    }
}
